<script lang="ts" setup>
  import { ref, watch, onMounted, onUnmounted } from 'vue';
  import MEcharts from '/@/components/MEcharts/MEcharts.vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data: { type: Object as () => any, required: true },
  });

  const chartRef = ref();

  const option = ref<any>({
    legend: {
      bottom: '2%',
      left: 'center',
    },
    series: [
      {
        animationDelay() {
          return Math.random() * 100;
        },
        animationEasing: 'exponentialInOut',
        animationType: 'scale',
        avoidLabelOverlap: false,
        color: ['#5ab1ef', '#8e7cc3', '#b6a2de', '#67e0e3', '#2ec7c9'],
        data: [
          { name: '90%以上', value: 1048 },
          { name: '80%-89%', value: 735 },
          { name: '70%-79%', value: 580 },
          { name: '60%-69%', value: 484 },
          { name: '60%以下', value: 484 },
        ],
        emphasis: {
          label: {
            fontSize: '12',
            fontWeight: 'bold',
            show: true,
          },
        },
        itemStyle: {
          // borderColor: '#fff',
          borderRadius: 10,
          borderWidth: 2,
        },
        label: {
          position: 'center',
          show: false,
        },
        labelLine: {
          show: false,
        },
        name: '命中率占比',
        radius: ['40%', '65%'],
        type: 'pie',
      },
    ],
    tooltip: {
      trigger: 'item',
    },
  });

  const myChart = ref<InstanceType<typeof MEcharts>>();
  const updateChart = () => {
    option.value.series[0].data = props.data ?? [];
    myChart.value?.resizeHandler();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      updateChart();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
  });

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container">
    <m-echarts :option="option"></m-echarts>
  </div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 11vh;
  }
</style>
